import type { Module } from 'vuex'
import type { IRootState } from '../types'
import type { ILoginState } from './types'
import type { IAccount } from 'network/login/types'
import router from '@/router'
import localCache from 'utils/cache'
import { mapMenusToRoutes, mapMeunsToPermissions } from 'utils/mapMenus'

import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusById
} from 'network/login/login'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state: () => ({
    token: '',
    userInfo: {},
    userMenus: [],
    permissions: []
  }),
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      // 将userMenus数据映射成为路由表
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      // 获取用户按钮的权限
      const permissions = mapMeunsToPermissions(userMenus)
      state.permissions = permissions
    }
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccount) {
      // 获取token
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('changeToken', token)
      localCache.setCache('token', token)
      //发送初始化的请求(完整的role/department)
      dispatch('getInitailDataAction', null, { root: true })

      // 请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 请求用户菜单
      const userMenusResult = await requestUserMenusById(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('changeUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)

      // 路由跳转
      router.replace('/main')
    },
    loadLocalLogin({ commit, dispatch }) {
      // 获取本地数据
      const token = localCache.getCache('token')
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      // 存在即赋值到vuex
      if (token) {
        commit('changeToken', localCache.getCache('token'))
        dispatch('getInitailDataAction', null, { root: true })
      }
      userInfo && commit('changeUserInfo', localCache.getCache('userInfo'))
      userMenus && commit('changeUserMenus', localCache.getCache('userMenus'))
    }
    // phoneLoginAction({ commit }, payload: any) {
    //   console.log('phoneLoginAction', payload)
    // }
  }
}

export default loginModule
